/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.vrangogym.faces.validation;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * A validator for email. Makes sure an email address is in the right
 * format.
 * @author Ulken
 */
@FacesValidator(value = "emailValidator")
public class EmailValidator implements Validator {

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        String email = (String) value;
        FacesMessage message = new FacesMessage();
        if (email.isEmpty()) {
            message.setSeverity(FacesMessage.SEVERITY_INFO);
            message.setSummary("Required");
            message.setDetail("Required");
            context.addMessage(null, message);
            throw new ValidatorException(message);
        } else if (!email.matches("(\\w+)(\\.\\w+)*@(\\w+)(\\.\\w+)*")) {
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("E-mail is not valid of a valid form");
            message.setDetail("Format: foo@bar.com");
            context.addMessage(null, message);
            throw new ValidatorException(message);
        }

    }
}
